/* eslint-disable no-undef */
import React, { Component } from 'react';
import { Table, Button, InputNumber, Upload, Icon, message, Modal } from 'antd';
import fetch from 'dva/fetch';
import ShowType from '../../../routes/common/showType';
import styles from '../../../index.less';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';

class StaticEditTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      gdsformconst: props.gdsformconst,
      app: props.app,
      headerConfig: props.headerConfig,
      showConfigList: props.showConfigList, /* 配置 */
      data: [],
      columns: [],
      disabled: props.disabled,
      editable: false, /* 编辑状态 */
      dataListAll: [], /* 表格原数据 */
      sActiveId: props.sActiveId, /* 窗体Id */
      btnAddShow: props.btnAddShow, /* 新增是否显示 */
      btnDelShow: props.btnDelShow, /* 删除是否显示 */
      btnUploadShow: props.btnUploadShow || false, /* 上传是否显示 */
      btnLookShow: props.btnLookShow || false, /* 上传图片查看 */
      scrollX: 0,
      totalRow: false, /* 是否存在汇总行 */
      totalMap: {}, /* 保存的数据汇总 */
      dataTotalFlag: false, /* 汇总数据是否已经加载 */
      currentKey: '',
      uploadInfo: '', /* 上传的信息 */
      upLoad: props.upLoad || false, /* 是否有上传 */
      mainData: props.mainData, /* 主表数据 */
      selectedRowKeys: [], /* 选中的行 */
      previewVisible: false, /* 图片预览弹窗 */
      previewImage: '', /* 预览图片地址 */
      masterConfig: props.masterConfig, /* 从表配置 */
    };
    this.count = 0; /* 行数 */
    this.tHeight = 0; /* 从表表内容高度 */
  }

  componentWillMount() {
    const { headerConfig, showConfigList } = this.state;
    this.handleEdit();
    /* 整合表头数据 */
    const columns = [];
    let scrollX = 37;
    let totalRow = false;
    const { totalMap } = this.state;
    /* 取出汇总列 */
    showConfigList.map((child) => {
      if (child.bSum) {
        totalRow = true;
        totalMap[`${child.sName}`] = '';
      }
      return child;
    });
    headerConfig.map((child, i) => {
      const iWidth = child.width === 0 ? 120 : child.width;
      scrollX += iWidth;
      const childColumns = {
        ...child,
        render: (text, record) => this.renderColumns(text, record, child.dataIndex),
      };
      const indexLine = child.title.indexOf('-');
      const title = child.title.substr(indexLine + 1);
      const childTitle = child.title.substr(0, indexLine);
      /* 此处判断为之前存在表头大类便进行合并 */
      const flag = i > 0 ? columns.filter(item => item.title === childTitle).length > 0 ? 1 : -1 : -1;
      if (indexLine > -1) {
        if (columns.length === 0 || flag === -1) {
          const obj = {
            title: childTitle,
            children: [{ ...childColumns, title }],
          };
          columns.push(obj);
        } else if (flag > -1) {
          /* 此处判断为之前存在表头大类便进行合并 */
          columns.filter(item => item.title === childTitle)[0].children.push({ ...childColumns, title });
        }
      } else {
        columns.push(childColumns);
      }
      return true;
    });
    this.setState({
      columns, scrollX, totalRow, totalMap,
    });
  }

  componentDidMount() {
    /* 计算行数 */
    const { currentPane, panes } = this.state.app;
    const indexPanel = panes.findIndex(item => item.key === currentPane.key);
    const tabContent = document.getElementsByClassName('ant-tabs-content')[0];
    const tabpanel = tabContent.children[indexPanel];
    const tabChild = tabpanel.getElementsByClassName('ant-tabs')[0];
    const tchildren = tabChild.getElementsByClassName('ant-spin-container')[0];
    const thead = tchildren.getElementsByClassName('ant-table-thead')[0].offsetHeight;
    const { clientHeight } = document.body;
    this.tHeight = clientHeight - 330 - thead;
    this.count = Math.floor(this.tHeight / 33) - 1;
    // if (this.props.onCount) {
    //   this.props.onCount(this.count);
    // }
    // if (SlaveTable && sId === '') {
    //   this.handleAdd(this.count, 'space');
  //  }
  }

  componentWillReceiveProps(nextProps) {
    const {
      dataListAll, disabled, dataTotal, mainData, selectedRowKeys,
    } = nextProps;
    const { dataTotalFlag, totalMap } = this.state;
    /* 数据 */
    const data = [];
    const totalMapValue = {};
    if (dataListAll.length > 0) {
      for (const child of dataListAll) {
        if (child.handleType !== 'del') {
          const value = {
            key: child.sId !== undefined ? child.sId : child.key,
            handleType: child.handleType,
          };
          for (const ckey of Object.keys(child)) {
            if (ckey !== 'key') {
              const firstKey = ckey.substring(0, 1);
              if (firstKey !== 'b') {
                value[ckey] = child[ckey];
              } else {
                value[ckey] = JSON.parse(child[ckey] ? child[ckey] : false);
              }
              /* 列表值改变后进行累加动作 */
              /* 此处没有使用editable来判断是否编辑状态才进行累加操作,因为在componentWillMount需要设置为True才能正确显示showType数据格式 */
              /* 使用disabled来判断是否为编辑状态进行累加 */
              if (!disabled) {
                if (totalMap[`${ckey}`] !== undefined) {
                  if (ckey.startsWith('i')) {
                    totalMapValue[`${ckey}`] = Number.parseInt(totalMapValue[`${ckey}`] !== undefined ? totalMapValue[`${ckey}`] : 0, 10) + Number.parseInt(child[ckey] !== '' ? child[ckey] : 0, 10);
                  } else if (ckey.startsWith('d')) {
                    totalMapValue[`${ckey}`] = Number.parseFloat(totalMapValue[`${ckey}`] !== undefined ? totalMapValue[`${ckey}`] : 0.0) + Number.parseFloat(child[ckey] !== '' ? child[ckey] : 0.0);
                  }
                }
              }
            }
          }
          data.push(value);
        }
      }
      /* 添加汇总数据 */
      if (dataTotal !== undefined && dataTotal !== null) {
        const { totalRow } = this.state;
        if (totalRow) {
          if (Object.keys(dataTotal).length > 0) {
            if (!dataTotalFlag) {
              data.push({ key: new Date().getTime(), dataTotal: true, ...dataTotal });
              this.setState({ totalMap: { ...totalMap, ...dataTotal }, dataTotalFlag: true });
            } else if (!disabled) {
              data.push({ key: new Date().getTime(), dataTotal: true, ...totalMapValue });
            } else {
              data.push({ key: new Date().getTime(), dataTotal: true, ...dataTotal });
            }
          }
        }
      }
    }
    /* 编辑与否状态 */
    if (disabled === false) {
      this.handleEdit();
    }
    this.setState({
      data, disabled, dataListAll, mainData, selectedRowKeys,
    });
  }

  onSelectChange = (selectedRowKeys, selectedRows) => {
    /* 过滤汇总项 */
    for (const child of selectedRows) {
      if (child.dataTotal !== undefined) {
        selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === child.key), 1);
      }
    }
    if (this.props.onSelectRowKeys) {
      this.props.onSelectRowKeys(selectedRowKeys);
    }
    this.setState({ selectedRowKeys });
  };

  handleChange(value, record, column, resultFields) {
    const flag = this.props.onSlaveAdd ? this.props.onSlaveAdd() : false;
    if (flag) return; /* 从表新增时判断主表必填字段是否填写 */
    if (value === 'ppopupValue') {
      // 回传record.key
      this.setState({ currentKey: record });
      this.props.handleRecordKey(record);
    }
    /* 过滤汇总项 */
    const data = this.state.data.filter(item => item.dataTotal !== true);
    const newData = [...data];
    const target = newData.filter(item => record === item.key)[0];
    if (target) {
      /* 过滤掉ppopupValue赋值,只保留handleType */
      if (value !== 'ppopupValue') {
        /* 存在赋值回带一般为下拉情况下 */
        if (resultFields !== undefined && resultFields !== '') {
          for (const item of resultFields) {
            /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
            const resultValue = {};
            let itemVlaue = '';
            /* 列表中的时间控件清空不会自动重置为NULL,需要手动处理避免影响默认值 */
            if (`${item.key}`.startsWith('t') && item.value === '') {
              itemVlaue = null;
            } else {
              itemVlaue = item.value;
            }
            if (item.key === column) {
              resultValue[`${column}`] = value;
            } else {
              resultValue[`${item.key}`] = itemVlaue;
            }
            const result = commonFunc.changeValue(resultValue);
            target[`${item.key}`] = result[`${item.key}`];
          }
        } else {
          /* 在配置赋值时需要把自身字段赋值配上，为了修正第一个获取不到的实际存储值的BUG */
          /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
          const resultValue = {};
          /* 列表中的时间控件清空不会自动重置为NULL,需要手动处理避免影响默认值 */
          if (column.startsWith('t') && value === '') {
            value = null;
          }
          resultValue[`${column}`] = value;
          const result = commonFunc.changeValue(resultValue);
          target[`${column}`] = result[`${column}`];
        }
      }
      if (target.handleType === undefined) {
        target.handleType = 'update';
      }
      this.setState({ data: newData });
      const { mainData } = this.state;
      if (mainData !== undefined) {
        this.props.handleTableData([...newData], record, mainData.sSearch, column);
      } else {
        this.props.handleTableData([...newData], record, '', column);
      }
    }
  }

  handleEdit() {
    const newData = [...this.state.data];
    this.setState({
      editable: true,
      data: newData,
    });
  }

  handleAdd = (num, type) => {
    if (type === 'add') {
      const flag = this.props.onSlaveAdd ? this.props.onSlaveAdd() : false;
      if (flag) return; /* 从表新增时判断主表必填字段是否填写 */
    }
    /* 获取唯一Id */
    const { token } = this.props.app;
    const url = `${config.server_host}getUuid/${num}`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    const newRow = [];
    const { showConfigList, mainData } = this.state;
    fetch(url, options).then(response => response.json()).then((json) => {
      const keys = json.dataset.rows;
      const data = this.state.data.filter(item => item.dataTotal !== true);
      for (let i = 0; i < keys.length; i += 1) {
        const newData = {
          key: keys[i],
        };
        if (!this.state.upLoad) {
          /* 是否有上传信息 */
          this.state.headerConfig.forEach((slaveChild) => {
            const ckey = slaveChild.dataIndex;
            const showConfig = showConfigList.filter(item => (item.sName === ckey))[0];
            /* 新增一行的默认值添加进列表提交数据 */
            const columnValue = commonFunc.listDefaultValueNewAdd(showConfig, '');
            newData[ckey] = columnValue;
          });
        } else {
          const { uploadInfo } = this.state;
          this.state.headerConfig.forEach((slaveChild) => {
            const ckey = slaveChild.dataIndex;
            if (ckey === 'sProductNo' || ckey === 'sProductName') {
              newData[ckey] = mainData[ckey] !== undefined ? mainData[ckey] : '';
            } else if (ckey === 'iOrder') {
              newData[ckey] = '';
            } else {
              newData[ckey] = uploadInfo[ckey];
            }
          });
        }
        newRow.push({ ...newData, handleType: 'add' });
      }
      this.setState({
        data: [...data, ...newRow],
        currentKey: keys[0],
      });
      if (mainData !== undefined) {
        this.props.handleTableData([...this.state.data], '', mainData.sSearch);
      } else {
        this.props.handleTableData([...this.state.data], '', '');
      }
    });
  };

  handleDel = () => {
    const { selectedRowKeys, mainData } = this.state;
    /* 过滤汇总项 */
    const data = this.state.data.filter(item => item.dataTotal !== true);
    const del = [];
    if (selectedRowKeys !== undefined && selectedRowKeys.length > 0) {
      selectedRowKeys.forEach((child) => {
        const index = data.findIndex(item => item.key === child);
        if (data[index].handleType === undefined || !data[index].handleType === 'add') {
          del.push(data[index]);
        }
        if (index >= 0) {
          if (!this.state.upLoad) {
            data.splice(index, 1);
            const delData = [];
            del.forEach((item) => {
              if (item.handleType === undefined || item.handleType === 'update') {
                delData.push({ ...item, handleType: 'del' });
              }
            });
            this.setState({
              data,
              selectedRowKeys: [],
            });
            if (mainData !== undefined) {
              this.props.handleTableData([...data, ...delData], '', mainData.sSearch);
              if (mainData.sSearch !== undefined && mainData.sSearch !== '') {
                this.props.onDelSlaveData(selectedRowKeys); /* 带搜索内容时，单独删除 */
              }
            } else {
              this.props.handleTableData([...data, ...delData], '');
            }
          } else {
            const { sActiveId } = this.state;
            const { token } = this.props.app;
            const value = { savePathStr: data[index].sPicturePath };
            const options = {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                authorization: token,
              },
              body: JSON.stringify(value),
            };
            const url = `${config.server_host}file/remove?sModelsId=${sActiveId}`;
            fetch(url, options).then(response => response.json()).then((json) => {
              if (json.code === 1) {
                data.splice(index, 1);
                message.success(json.msg);
                const delData = [];
                del.forEach((item) => {
                  if (item.handleType === undefined || item.handleType === 'update') {
                    delData.push({ ...item, handleType: 'del' });
                  }
                });
                this.setState({
                  data,
                  selectedRowKeys: [],
                });
                this.props.handleTableData([...data, ...delData]);
              } else {
                message.error(json.msg);
              }
            });
          }
        }
      });
    } else {
      const { gdsformconst } = this.state;
      if (gdsformconst !== undefined) {
        const selectedRowKeysNo = gdsformconst.filter(item => (item.sName === 'selectedRowKeysNo'))[0].showName;
        message.warning(selectedRowKeysNo);
      }
    }
  };

  /* 点击行事件 */
  handleRowClick=(record) => {
    if (this.props.handleRowClick !== undefined) {
      this.props.handleRowClick(record);
    }
  };

  handleUploadChange = (info) => {
    /* 获取上传后的一些信息 */
    const { file } = info;
    if (file.response) {
      const sPicturePath = file.response.dataset.rows[0].savePathStr;
      const uploadInfo = {
        sPicturePath,
        sFileName: file.name,
      };
      this.setState({ uploadInfo });
      this.handleAdd(1, 'add');
    }
  };
  handlePreview = () => {
    /* 查看 */
    const { selectedRowKeys, data } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length === 0) {
      return message.warning('请选择一条数据进行查看');
    } else {
      const dataSelect = data.filter(item => item.key === selectedRowKeys[0]);
      const { sActiveId } = this.state;
      const { token } = this.props.app;
      const { sPicturePath } = dataSelect[0];
      const previewUrl = `${config.server_host}file/download?sModelsId=${sActiveId}&token=${token}&savePathStr=${sPicturePath}`;
      this.setState({
        previewImage: dataSelect.length > 0 ? previewUrl : '',
        previewVisible: true,
      });
    }
  };
  handleModalCancel = () => {
    /* 关闭弹窗 */
    this.setState({ previewVisible: false });
  };
  renderColumns = (text, record, column) => {
    const {
      showConfigList, disabled, editable, sActiveId, mainData,
    } = this.state;
    const { onSlaveAdd } = this.props;
    const showConfig = showConfigList.filter(item => (item.sName === column))[0];
    const showConfigCopy = { ...showConfig };
    if (record.sProductId && showConfig.sName === 'sProductUnit') {
      showConfigCopy.bReadonly = true;
    }
    /* 判断配置是否有SQL条件值, 有的话给相应的sql条件赋值 */
    let sSql = []; /* 配置中SQL条件 */
    const sSqlCondition = {}; /* sql条件配置 */
    if (showConfigCopy.sSqlCondition !== undefined && showConfigCopy.sSqlCondition !== '') {
      sSql = showConfigCopy.sSqlCondition.split(',');
    }
    const { dataListAll } = this.state;
    if (sSql.length > 0) {
      sSql.forEach((child) => {
        if (child) {
          child = child.trim();
        }
        const dataList = dataListAll.filter(item => (item.key === this.state.currentKey));
        let sValue = dataList.length > 0 && dataList[0][child] !== undefined
          ? dataList[0][child].split('[-]')[0] === ''
            ? {}
            : dataList[0][child].split('[-]')[0]
          : {};
        if (mainData && mainData[child]) {
          sValue = mainData[child];
        } else {
          sValue = {};
        }
        sSqlCondition[child] = sValue;
      });
    }
    const {
      handleModalPane, dataName, dataType, comboxSelect, onClose,
    } = this.props;
    /* 列表默认值 */
    const columnValue = commonFunc.listDefaultValue(showConfigCopy, text);
    const { masterConfig } = this.state;
    const sTbName = masterConfig !== undefined ? masterConfig.sTbName : '';
    let dTotalMoneyMin;
    let dTotalMoneyMax;
    if ((sTbName === 'cahreceiptslave' || sTbName === 'cahpaymentslave') && column === 'dTotalMoney') {
      /* 收款金额最大值与最小值设置 */
      const { dBalanceMoney } = record; /* 余额 */
      const dRoundingMoney = record.dRoundingMoney !== undefined ? record.dRoundingMoney : 0; /* 舍入 */
      if (dBalanceMoney >= 0) {
        dTotalMoneyMin = 0;
        dTotalMoneyMax = dBalanceMoney - dRoundingMoney;
      } else {
        dTotalMoneyMin = dBalanceMoney - dRoundingMoney;
        dTotalMoneyMax = 0;
      }
    }
    const staticEditTableProps = {
      sActiveId,
      editable,
      value: columnValue,
      showConfig: showConfigCopy,
      disabled,
      app: this.props.app,
      form: this.props.form,
      handleModalPane,
      dataName,
      dataType,
      sSqlCondition: Object.keys(sSqlCondition).length > 0 ? sSqlCondition : '',
      dTotalMoneyMin,
      dTotalMoneyMax,
      sTbName,
      onSlaveAdd,
      onClose,
    };
    /* 是否有存在可输入可选择控件, 如果有，加标识,并判断是否是本行，本行才渲染 */
    const comboxIndex = comboxSelect !== undefined ? comboxSelect.findIndex(item => (item === column)) : -1;
    staticEditTableProps.currentKey = false;
    if (comboxIndex >= 0) {
      staticEditTableProps.comboxSelect = true;
      if (this.state.currentKey === record.key) {
        staticEditTableProps.currentKey = true;
      }
    } else {
      staticEditTableProps.comboxSelect = false;
    }
    if (record.dataTotal !== undefined) {
      return (
        disabled
          ? <InputNumber defaultValue={text} disabled={disabled} className={styles.inputNum} />
          : <div className={styles.editSpan}><span>{text}</span></div>
      );
    } else if (column.startsWith('i')) {
      return (<ShowType
        sName={column}
        {...staticEditTableProps}
        maxLength={11}
        onChange={(value, resultFields) => this.handleChange(value, record.key, column, resultFields)}
      />);
    } else if (column.startsWith('d')) {
      return (<ShowType
        sName={column}
        maxLength={18}
        {...staticEditTableProps}
        onChange={(value, resultFields) => this.handleChange(value, record.key, column, resultFields)}
      />);
    } else {
      return (<ShowType
        sName={column}
        {...staticEditTableProps}
        onChange={(value, resultFields) => this.handleChange(value, record.key, column, resultFields, staticEditTableProps.comboxSelect)}
      />);
    }
  };
  render() {
    const {
      selectedRowKeys, columns, disabled, scrollX, previewVisible, previewImage,
    } = this.state;
    const {
      btnAddShow, btnDelShow, data, btnUploadShow, btnLookShow,
    } = this.state;
    const btnAdd = btnAddShow === false ? 'none' : 'inline-block';
    const btnDel = btnDelShow === false ? 'none' : 'inline-block';
    const btnUpload = btnUploadShow === false ? 'none' : 'inline-block';
    const btnLook = btnLookShow === false ? 'none' : 'inline-block';
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        style: record.dataTotal === true ? { display: 'none' } : {},
      }),
      type: this.props.type === undefined ? 'checkbox' : this.props.type,
    };
    const { sActiveId } = this.state;
    const { token } = this.props.app;
    const uploadProps = {
      action: `${config.server_host}file/upload?sModelsId=${sActiveId}&token=${token}`,
      onChange: this.handleUploadChange,
      accept: 'image/*',
      beforeUpload: () => {
        /* 查看时不可上传 */
        if (disabled) return false;
      },
    };
    const divProps = Object.assign({}, uploadProps);
    return (
      <div>
        <div className={styles.tableOption}>
          <Upload {...divProps}>
            <Button disabled={disabled} style={{ display: btnUpload }}>
              <Icon type="upload" /> 上传
            </Button>
          </Upload>
          <Button disabled={disabled} style={{ display: btnLook }} onClick={this.handlePreview}>查看</Button>
          <Button onClick={this.handleAdd.bind(this, 1, 'add')} disabled={disabled} style={{ display: btnAdd }}>增行</Button>
          <Button onClick={this.handleDel} disabled={disabled} style={{ display: btnDel }} className={styles.del}>删行</Button>
        </div>
        <div id="staticEditTable">
          <Table
            bordered
            size="middle"
            columns={columns}
            dataSource={data}
            pagination={false}
            rowSelection={rowSelection}
            className={disabled ? styles.disabledProup : styles.proup}
            id={data.length === 0 ? 'unDataBox' : 'dataBox'}
            scroll={{ x: scrollX, y: this.count * 35 }}
            onRow={(record) => {
              return {
                onClick: () => { this.handleRowClick(record); }, // 点击行
              };
            }}
          />
        </div>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleModalCancel}
          width={1000}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default StaticEditTable;

